package chat.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.util.HtmlUtils;

import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Map;
import java.util.regex.Pattern;


public class reveryTool {

    /*
    * 复制对象
    * AssignedObj 赋值对象
    * sourceObj 源对象
    * */
    public static void copyObject(Object AssignedObj,Object sourceObj)throws Exception{
        if(AssignedObj==null || sourceObj==null){
            return;
        }

        Class<?> clazz = AssignedObj.getClass();

        Field[] fields=clazz.getDeclaredFields();
        for(int i = 0; i < fields.length; i++){
            fields[i].setAccessible(true);
            Object sourceValue=fields[i].get(AssignedObj);
            fields[i].set(sourceObj,sourceValue);
        }
    }

    /*
     * 通过httprequery获取的参数，注入到实体类中
     * */
    public static void implantData(Object formObj,Map<String,String[]> requeryData)throws Exception{
        try{
            Class<?> clazz = formObj.getClass();

            Field[] fields=clazz.getDeclaredFields();
            for(int i = 0; i < fields.length; i++){
                Field field = fields[i];
                field.setAccessible(true);

                String[] value = requeryData.get(field.getName());
                if(value!=null){
                    System.out.println(field.getType()+"    "+field.getName());
                    switch (field.getType().toString()){
                        case "class java.lang.Long":
                            if(!StringUtils.isEmpty(value[0])){
                                field.set(formObj,Long.valueOf(value[0]));
                            }
                            break;
                        case "class java.lang.Integer":
                            if(!StringUtils.isEmpty(value[0])){
                                field.set(formObj,Integer.valueOf(value[0]));
                            }
                            break;
                        case "class java.lang.String":
                            field.set(formObj,htmlEnCode(String.valueOf(value[0])));
                            break;
                        default:
                            System.out.println("未定义数据类型："+field.getType());
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();

            throw new Exception("不符合预期的数据类型！");
        }
    }

    /*
    * 时间格式化
    * */
    static final ZoneId zone = ZoneId.systemDefault();
    public static String timeToString(Long time){
        Date date = new Date(time);
        LocalDateTime dateTime = LocalDateTime.ofInstant(date.toInstant(),zone);
        return dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    /*
    * 获取根目录
    * */
    public static String getRootPath(Object o){
        String filePath = o.getClass().getResource("").getPath();
        String[] filePaths = filePath.split("/classes/");
        return filePaths[0]+"/";
    }

    /*
    * htmlEnCode
    * */
    public static String htmlEnCode(String str){
        return HtmlUtils.htmlEscape(str);
    }

    /*
    * htmlDecode
    * */
    public static String htmlDecode(String str){
        return HtmlUtils.htmlUnescape(str);
    }


    /*
    * MD5
    * */
    public static String md5(String str){
        String md5 = DigestUtils.md5DigestAsHex(str.getBytes());
        return md5;
    }


    /*
     * <h1>验证手机号</h1>
     *   tel 手机号
     * */
    public static Boolean isTel(String tel){
        if(tel!=null){
            String regex = "^1[^124]\\d{9}$";
            Pattern p = Pattern.compile(regex);
            return p.matcher(tel).matches();
        }

        return false;
    }


    /*
     * 同步网络请求
     * url
     * post 传递参数
     * dataType 返回数据格式，默认返回repons
     * */
    public static JSONObject http(String url){ return (JSONObject)reveryTool.http(url,null,"json"); }
    public static JSONObject http(String url,Object data){return (JSONObject)reveryTool.http(url,data,"json"); }
    public static Object http(String url,Object data,String dataType){
        Response response = null;
        try{
            OkHttpClient client = new OkHttpClient();

            Request.Builder builder = new Request.Builder();

            if(data!=null){
                RequestBody body=null;
                if(data instanceof String){
                    System.out.println(String.valueOf(data));
                    body = RequestBody.create(MediaType.parse("text/plain; charset=utf-8"),String.valueOf(data));
                    System.out.println(body.toString());
                }else{
                    FormBody.Builder formBody = new FormBody.Builder();

                    Map<String,String> dataMap = (Map<String,String>)data;
                    for (String key : dataMap.keySet()) {
                        formBody.add(key,dataMap.get(key));
                    }

                    body = formBody.build();
                }

                builder.post(body);
                System.out.println(builder.post(body));
            }else{
                builder.get();
            }

            Request request = builder.url(url).build();
            Call call = client.newCall(request);

            //同步线程处理
            response = call.execute();

            if("text".equals(dataType)){
                return response.body().string();
            }else if("json".equals(dataType)){
                JSONObject json = JSON.parseObject(response.body().string());
                if(json==null){
                    System.out.println("http error : "+response.body().string());
                }
                return json;
            }else{
                System.out.println(response.body());
                return response;
            }

        }catch (Exception $e){
            $e.printStackTrace();
            System.out.println("http请求错误！");
            if(response!=null){
                try{
                    System.out.println("http请求错误！返回结果： "+response.body().string());
                }catch (Exception e2){
                    e2.printStackTrace();
                }
            }

        }

        return null;
    }


    public static void sendMessage(String tel){

    }

    public static Long getRomdom(){

        long max = 0xFFFFFFFFL;
        long rand = (long) (max * Math.random());
        return rand;

    }
}
